package com.accp.taobao.service;

import com.accp.taobao.model.AirConditioner;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于提取数据对象的线程
 */
public class ExtractDataThread extends Thread {
    private int key;
    private String cleanedData;
    private HashMap<Integer, AirConditioner> infoMap;

    public ExtractDataThread(int key, String cleanedData, HashMap<Integer, AirConditioner> infoMap) {
        this.key = key;
        this.cleanedData = cleanedData;
        this.infoMap = infoMap;
    }

    @Override
    public void run() {
        //由于Map的节点已在主线程中创建，键与线程的映射唯一，故此处不考虑同步问题;
        Pattern pattern=Pattern.compile("(<em title=\"(\\d+?\\.\\d\\d)\")|(<(p|div) class=\"productTitle[^\\>]+?>[^<]*?<[^\\>]+?>([\\d\\D]*?)</a>)|(((\\d+?(\\.\\d)?)(万?))笔)");
        Matcher matcher=pattern.matcher(cleanedData);
        AirConditioner airConditioner =new AirConditioner();
        while (matcher.find()){
            if (matcher.group(2)!=null){
                airConditioner.setPrice(Double.parseDouble(matcher.group(2)));
            }else if(matcher.group(5)!=null){
                airConditioner.setName(matcher.group(5).replaceAll("\r|\n",""));
            }else if(matcher.group(8)!=null){
                //处理x.x万格式的数据
                double salesNum=Double.parseDouble(matcher.group(8));
                if(matcher.group(10).equals("万")){
                    salesNum*=10000;
                }
                airConditioner.setSalesNum((int) salesNum);
            }
        }
        infoMap.put(key, airConditioner);
    }
}
